package com.giantlizard.cloud.auth.service.impl;

import com.giantlizard.cloud.api.service.RemoteUserService;
import com.giantlizard.cloud.base.entity.SysRes;
import com.giantlizard.cloud.base.entity.SysRole;
import com.giantlizard.cloud.base.entity.SysUser;
import com.giantlizard.cloud.base.generics.R;
import com.giantlizard.cloud.common.security.model.LoginUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private RemoteUserService remoteUserService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            // 远程调用获取用户信息
            R<SysUser> userResult = remoteUserService.getUserInfo(username);
            if (!userResult.getCode().equals(R.SUCCESS) || Objects.isNull(userResult.getData())) {
                throw new UsernameNotFoundException("用户不存在");
            }
            SysUser sysUser = userResult.getData();
            // 获取用户权限
            R<List<SysRole>> roles = remoteUserService.selectRoleByUserId(sysUser.getUserId());
            if (!roles.getCode().equals(R.SUCCESS) || Objects.isNull(roles.getData())) {
                throw new UsernameNotFoundException("用户不存在");
            }

            List<SysRole> role = roles.getData();
            List<SysRes> resList = new ArrayList<>();
            for (SysRole sysRole : role) {
                resList.addAll(sysRole.getResList());
            }
            List<String> resUrlList = resList.stream().map(SysRes::getResUrl).collect(Collectors.toList());
            LoginUser loginUser = new LoginUser();
            BeanUtils.copyProperties(sysUser, loginUser);
            loginUser.setPassword(sysUser.getPassword());
            loginUser.setRoleList(role);
            loginUser.setResList(resList);
            loginUser.setPermissions(resUrlList);
            return loginUser;
        } catch (Exception e) {
            throw new UsernameNotFoundException("用户认证失败：" + e.getMessage());
        }
    }

} 